package site.lanmushan.generate.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.Properties;

/**
 * @author Administrator
 */
public class VelocityUtil {

    public static Template getVelocityTemplateByClassPath(String tplName) {
        Properties properties = new Properties();
        //设置velocity资源加载方式为class
        properties.setProperty("resource.loader", "class");
        //设置velocity资源加载方式为file时的处理类
        properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngine ve = new VelocityEngine(properties);
        //处理中文问题
        ve.setProperty(Velocity.INPUT_ENCODING, "utf-8");
        ve.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
        try {
            //初始化模板
            ve.init();
            //Velocity模板的名称
            Template template = ve.getTemplate(tplName, "utf-8");
            return template;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }
    public static Template getVelocityTemplateByPath(String path,String tplName) {
        Properties properties = new Properties();
        //设置velocity资源加载方式为class
        //设置velocity资源加载方式为file时的处理类
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
        VelocityEngine ve = new VelocityEngine(properties);
        //处理中文问题
        ve.setProperty(Velocity.INPUT_ENCODING, "utf-8");
        ve.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
        try {
            //初始化模板
            ve.init();
            //Velocity模板的名称
            Template template = ve.getTemplate(tplName, "utf-8");
            return template;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    public static void main(String[] args) {
        Template tpl = getVelocityTemplateByClassPath("tpl/t1.java");
        StringWriter sw = new StringWriter();
        VelocityContext ctx = new VelocityContext();
        ctx.put("xxx", "xxx");
        tpl.merge(ctx, sw);
        System.out.println(sw.toString());
    }
}
